package com.cjq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cjq.domain.User;
import com.cjq.service.UserService;
import com.cjq.utils.JwtUtils;
import com.cjq.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author junqiancai@foxmail.com
 * @since 2021/6/9 21:28
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @GetMapping("/test")
    public String test(){
        return "可正常访问";
    }


    /**
     * 自定义了登出路径，原来的默认/logout还是可以访问，只是点击后无效,此路径携带的token已被拦截且验证正确
     * @param request
     * @return
     */
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        //登出时根据请求头中的token删除redis中的key
        String header = request.getHeader(JwtUtils.AUTHENTICATION);
        if(StringUtils.hasText(header)){
            String jwtToken = header.replaceAll("bearer ", "");
            if(StringUtils.hasText(jwtToken)){
                redisTemplate.delete(JwtUtils.REDIS_PREFIXED+jwtToken);
            }
        }
        return Result.succeed(200,"登出成功");
    }

    @PreAuthorize("hasAnyRole('ADMIN','SUPER')")
    @GetMapping("/departments")
    public Result getDepartments()
    {
        final QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT department");
        String[] departments = userService.list(wrapper).stream().map(User::getDepartment).toArray(String[]::new);
        Integer code=Result.SUCCESS;
        if(departments.length==0)code=Result.NO_CONTENT;
        return Result.succeed(code,"查询成功",departments);
    }

    @PreAuthorize("hasAnyRole('ADMIN','SUPER')")
    @GetMapping("/majors")
    public Result getMajors(@RequestParam("department")String department)
    {
        final QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT major")
                .eq("department",department);
        String[] majors = userService.list(wrapper).stream().map(User::getMajor).toArray(String[]::new);
        Integer code=Result.SUCCESS;
        if(majors.length==0)code=Result.NO_CONTENT;
        return Result.succeed(code,"查询成功",majors);
    }

    @PreAuthorize("hasAnyRole('ADMIN','SUPER')")
    @GetMapping("/className")
    public Result getDepartments(@RequestParam("department")String department, @RequestParam("major") String major)
    {
        final QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT grade, class_name")
                .eq("department",department)
                .eq("major",major);
        String[] classNames = userService.list(wrapper).stream()
                .map(user-> user.getGrade()+"级"+user.getClassName())
                .toArray(String[]::new);
        Integer code=Result.SUCCESS;
        if(classNames.length==0)code=Result.NO_CONTENT;
        return Result.succeed(code,"查询成功",classNames);
    }

    @PreAuthorize("hasAnyRole('ADMIN','SUPER')")
    @PostMapping("/accounts")
    public Result getAccounts(@RequestBody(required = false) User user,
                              @RequestParam(value = "pageSize",required = false,defaultValue = "10") Integer pageSize,
                              @RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum)
    {
        final LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>(user);
        wrapper.select(User::getId,User::getUsername,User::getUserType,User::getRealName,User::getPhone,User::getSchool,
                User::getDepartment,User::getGrade,User::getMajor,User::getClassName);
        final IPage<User> userIPage = userService.selectAccountByPage(new Page<>(pageNum, pageSize), wrapper);
        Integer code = Result.SUCCESS;
        if(userIPage==null || userIPage.getRecords().size()==0)code=Result.NO_CONTENT;
        return Result.succeed(code,"查询成功",userIPage);
    }
}
